package com.ying.tests.CCCbasis.Test3Socket;


import java.io.*;
import java.net.*;

public class Test3NetworkServer {

    public static void main(String[] args) {
        args = new String[]{"127.0.0.1", "8888"};
        test3(args);            // Socket服务端实例
    }


    // Socket服务端实例
    private static void test3(String[] args) {
        int port = Integer.parseInt(args[1]);
        Thread thread = null;
        try {
            thread = new ServerTest(port);
            thread.run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


class ServerTest extends Thread {
    private ServerSocket serverSocket;

    public ServerTest(int port) throws IOException {
        serverSocket = new ServerSocket(port);
//        serverSocket.setSoTimeout(30000);
        System.out.println("服务端准备就绪");
    }

    public void run() {
        while (true) {
            try {
                System.out.println("本机端口号：" + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("远程客户端地址：" + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("Hello from " + server.getLocalSocketAddress() + "\nGoodbye!");
                server.close();
            } catch (SocketTimeoutException e) {
                System.out.println("Socket timed out!");
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }
}
